package com.sgb.kjwl.view.ui.activity.home;

import static com.blankj.utilcode.util.SnackbarUtils.dismiss;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;

import androidx.core.view.ViewCompat;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.google.android.flexbox.FlexWrap;
import com.google.android.flexbox.FlexboxLayout;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.sgb.contract.view.widget.TagBuilder;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivitySearchShopFirstBinding;
import com.sgb.kjwl.di.home.DaggerHomeComponent;
import com.sgb.kjwl.di.home.HomeModule;
import com.sgb.kjwl.model.entity.request.MaterialFilterJson;
import com.sgb.kjwl.model.entity.shopping.SearchTagEntity;
import com.sgb.kjwl.model.entity.user.GoodsListEntity;
import com.sgb.kjwl.utils.FileUtils;
import com.swgk.core.util.UiUtil;
import com.sgb.kjwl.view.ui.activity.material.ConcreteDetailActivity2;
import com.sgb.kjwl.view.ui.activity.material.GoodsSearchResultActivity;
import com.sgb.kjwl.view.ui.activity.self.shop.ShopGoodsDetailActivity;
import com.sgb.kjwl.view.ui.adapter.search.MaterialAdapter;
import com.sgb.kjwl.viewmodel.home.SearchShopFirstModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.dialog.RoundDialog;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.util.MToast;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import javax.inject.Inject;

public class SearchShopFirstActivity extends AppActivity {
    private ActivitySearchShopFirstBinding binding;
    @Inject
    SearchShopFirstModel viewModel;
    private MaterialAdapter materialAdapter;
    private List<String> searchData = new ArrayList<>();
    private List<SearchTagEntity> searchTagEntities = new ArrayList<>();

    public static void start(Context context, boolean isHomePage) {
        Intent intent = new Intent();
        intent.setClass(context, SearchShopFirstActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        context.startActivity(intent);
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerHomeComponent.builder().appComponent(appComponent).homeModule(new HomeModule(this)).build().inject(this);

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }


    @Override
    protected void initView() {
        binding = DataBindingUtil.setContentView(SearchShopFirstActivity.this, R.layout.activity_search_shop_first);
        initEtSearchView();
        viewModel.getGoodsList(false);
        viewModel.searchCategory();
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
                           public void run() {
                               InputMethodManager inputManager =
                                       (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                               inputManager.showSoftInput(binding.etView, 0);
                           }
                       },
                200);

        binding.searchTagList.setMaxLine(3);
        binding.searchTagList.setFlexWrap(FlexWrap.WRAP);
        binding.hostSearchTagList.setMaxLine(3);
        binding.hostSearchTagList.setFlexWrap(FlexWrap.WRAP);

        binding.shopList.setLayoutManager(new LinearLayoutManager(getActivity()));
        materialAdapter = new MaterialAdapter(this, null, false);
        binding.shopList.setAdapter(materialAdapter);
        binding.btnSearchChange.setOnClickListener(view -> {
            viewModel.getGoodsList(true);
        });
        binding.deleteImg.setOnClickListener(view -> {
            showDialog();
        });
        binding.tvSearch.setOnClickListener(v -> {
            if (TextUtils.isEmpty(binding.etView.getText().toString().trim())) {
                MToast.showToast(SearchShopFirstActivity.this, "请输入关键字");
            } else {
                doSearch();
            }
        });
        binding.ivBack.setOnClickListener(v ->
                finish());
        materialAdapter.setOnItemClick(new AdapterOnItemClick<GoodsListEntity>() {
            @Override
            public void onItemClick(GoodsListEntity goodsListEntity, int position) {
                if ("7".equals(goodsListEntity.getId())) {
                    MaterialFilterJson filterJson = new MaterialFilterJson();
                    filterJson.setStrengthId(goodsListEntity.getSort());
                    ConcreteDetailActivity2.start(getActivity(), goodsListEntity.getId(), filterJson);
                } else {
                    ShopGoodsDetailActivity.start(SearchShopFirstActivity.this, goodsListEntity.getId(), "", goodsListEntity.getSkuid());
                }
            }
        });
    }

    /**
     * 初始化 搜索功能
     */
    private void initEtSearchView() {
        binding.etView.setFocusable(true);
        binding.etView.setFocusableInTouchMode(true);
        binding.etView.requestFocus();
        binding.tvSearch.setOnClickListener(this);
        binding.etView.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
        binding.tvSearchDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                binding.etView.setText("");
            }
        });
        binding.etView.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (TextUtils.isEmpty(s.toString().trim())) {
                    binding.tvSearchDelete.setVisibility(View.GONE);
                } else {
                    binding.tvSearchDelete.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        binding.etView.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
                    if (TextUtils.isEmpty(binding.etView.getText().toString().trim())) {
                        MToast.showToast(SearchShopFirstActivity.this, "请输入关键字");
                        InputMethodManager inputManager =
                                (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                       if (inputManager!=null){
                           inputManager.hideSoftInputFromWindow(v.getWindowToken(),0);
                       }
                        return true;
                    }
                    doSearch();
                }
                return false;
            }
        });

    }


    private void doSearch() {
        String searchText = binding.etView.getText().toString().trim();
        GoodsSearchResultActivity.start(SearchShopFirstActivity.this, searchText);
        FileUtils.setJsonTxt(searchText, SearchShopFirstActivity.this);
        closeKeybord();
        finish();
    }

    @Override
    protected void init() {
        if (TextUtils.isEmpty(FileUtils.readTextFile())) {
            binding.searchTagList.setVisibility(View.GONE);
            binding.layoutSearch.setVisibility(View.GONE);
        } else {
            searchData = JsonToObject(FileUtils.readTextFile(), new TypeToken<List<String>>() {
            }.getType());
            for (int i = 0; i < searchData.size(); i++) {
                SearchTagEntity searchTagEntity = new SearchTagEntity();
                searchTagEntity.dmmc = searchData.get(i);
                searchTagEntities.add(searchTagEntity);
            }
            for (int i = 0; i < searchTagEntities.size(); i++) {
                binding.searchTagList.addView(createNewFlexItemTextView(searchTagEntities.get(i), false));
            }
            binding.layoutSearch.setVisibility(View.VISIBLE);
            binding.searchTagList.setVisibility(View.VISIBLE);

        }
    }

    public void showDialog() {
        RoundDialog.Builder builder = new TagBuilder(SearchShopFirstActivity.this)
                .title("温馨提示")
                .content("确定删除最近搜索记录？")
                .contentGravity(Gravity.CENTER)
                .cancelable(false)
                .confirmCallback(v -> {
                    dismiss();
                    binding.layoutSearch.setVisibility(View.GONE);
                    binding.searchTagList.setVisibility(View.GONE);
                    FileUtils.deleteDirectory();
                });
        builder.singleBtn(false);
        builder.confirm("确定");
        builder.cancel("取消");
        builder.show();
    }

    //加载或更新数据//是否满足显示换一换的条件
    public void updateData(List<GoodsListEntity> list, boolean isShowChangeBtn) {
        materialAdapter.setDatas(list);
        binding.btnSearchChange.setVisibility(isShowChangeBtn ? View.VISIBLE : View.GONE);
    }

    public void updateDataTag(List<SearchTagEntity> list) {
        if (list != null && list.size() > 0) {
            binding.hostSearchTagList.setVisibility(View.VISIBLE);
            binding.tvHostSearch.setVisibility(View.VISIBLE);
            for (int i = 0; i < list.size(); i++) {
                if (i == 0 || i == 1 || i == 2) {
                    binding.hostSearchTagList.addView(createNewFlexItemTextView(list.get(i), true));
                } else {
                    binding.hostSearchTagList.addView(createNewFlexItemTextView(list.get(i), false));
                }
            }
        } else {
            binding.hostSearchTagList.setVisibility(View.GONE);
            binding.tvHostSearch.setVisibility(View.GONE);
        }
    }


    @Override
    public void onBackPressed() {
        finish();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    /**
     * 将字符串转换为 对象
     *
     * @param json
     * @param type
     * @return
     */
    public static <T> T JsonToObject(String json, Type type) {
        Gson gson = new Gson();
        return gson.fromJson(json, type);
    }

    /**
     * 动态创建TextView
     *
     * @param entity
     * @return
     */
    private TextView createNewFlexItemTextView(final SearchTagEntity entity, boolean ischeck) {
        TextView textView = new TextView(this);
        textView.setGravity(Gravity.CENTER);
        textView.setText(entity.dmmc);
        textView.setTextSize(12);
        if (ischeck) {
            textView.setTextColor(getResources().getColor(R.color.color_FF7C38));
        } else {
            textView.setTextColor(getResources().getColor(R.color.color_333333));
        }
        textView.setBackgroundResource(R.drawable.corner5_white_bg);
        textView.setLines(1);
        textView.setEllipsize(TextUtils.TruncateAt.END);
        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                binding.etView.setText(entity.dmmc);
                doSearch();
            }
        });
        int padding = UiUtil.dip2px(this, 5);
        int paddingLeftAndRight = UiUtil.dip2px(this, 8);
        int Height = UiUtil.dip2px(this, 28);
        ViewCompat.setPaddingRelative(textView, paddingLeftAndRight, 0, paddingLeftAndRight, 0);
        FlexboxLayout.LayoutParams layoutParams = new FlexboxLayout.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                Height);
        layoutParams.setMargins(padding, padding, padding, 0);
        textView.setLayoutParams(layoutParams);
        return textView;
    }

}
